package org.zhuzx.util.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class ReplaceBeanPropertyFactory extends ReplaceBeanPropertyConfiguration
		implements BeanFactoryPostProcessor {

	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println(">>>>调用ReplaceBeanPropertyFactory批量替换属性" + targetPropertyName);
		if (needReplacedBeanNames != null) {
			for (String beanName : needReplacedBeanNames) {
				executeOnBean(beanFactory, beanName);
			}
		}
		if (needReplacedBeanPattern != null) {
			String[] beanNames = beanFactory.getBeanDefinitionNames();
			for (String beanName : beanNames) {
				if (beanName.matches(needReplacedBeanPattern)) {
					executeOnBean(beanFactory, beanName);
				}
			}
		}
	}
	
	private void executeOnBean(ConfigurableListableBeanFactory beanFactory, String beanName) {
		BeanDefinition def = beanFactory.getBeanDefinition(beanName);
		if (def == null) {
			throw new RuntimeException("找不到名称为" + beanName + "的bean");
		} else if (def.getAttribute(targetPropertyName) == null) {
			throw new RuntimeException("名称为" + beanName + "的bean没有" + targetPropertyName + "属性");
		}
		def.setAttribute(targetPropertyName, replacementPropertyValue);
	}

}